package sample;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import sample.domain.BijiaoResult;
import sample.domain.People;
import sample.util.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Controller {
    @FXML
    private ListView leftList;
    @FXML
    private ListView rightList;
    @FXML
    private ListView resultList;

    @FXML
    TableView<BijiaoResult> resultTableView; //声明TableView表格
    @FXML
    private TableColumn<BijiaoResult, String> errorFileName;   //声明表格中的列
    @FXML
    private TableColumn<BijiaoResult, String> errorNumber;
    @FXML
    private TableColumn<BijiaoResult, String> errorDescribe;


    ObservableList<String> leftFlileDataList = FXCollections.observableArrayList();
    boolean addLeftClick = false;

    ObservableList<String> rightFlileDataList = FXCollections.observableArrayList();
    boolean addRightClick = false;

    ObservableList<String> resultFlileDataList = FXCollections.observableArrayList();

    List<People> resultPeopleList = new ArrayList<>();
    List<People> resultLeftPeopleList = new ArrayList<>();
    List<People> resultRightPeopleList = new ArrayList<>();

    //创建集合userList
    ObservableList<BijiaoResult> bijiaoResultList = FXCollections.observableArrayList();


    public void xuanzeFile(String state) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择文件");
//        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("doc", "*.doc"),
//                new FileChooser.ExtensionFilter("docx", "*.docx"),
//                new FileChooser.ExtensionFilter("xls", "*.xls"),
//                new FileChooser.ExtensionFilter("xlsx", "*.xlsx"));
        // 显示文件选择对话框，并获取选中的文件（如果有）
        File file = fileChooser.showOpenDialog(null);
        if (file != null && (file.getAbsolutePath().indexOf(".doc") > 0 || file.getAbsolutePath().indexOf(".xls") > 0 || file.getAbsolutePath().indexOf(".xlsx") > 0)) {
            if (file.getAbsolutePath().indexOf(".docx") > 0) {
                return;
            }
            String fileText = file.getAbsolutePath();
            fileText = fileText + "——" + FileUtil.splitName(fileText);
            // 处理选中的文件
            if (state.equals("left")) {
                leftFlileDataList.add(fileText);
            } else if (state.equals("right")) {
                rightFlileDataList.add(fileText);
            }
        }
        notPresentFile();
    }

    public void xuanzeFiles(String state) {
        // 创建文件夹选择器
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择文件夹");
        // 设置初始目录（可选）
//        directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        // 显示文件夹选择器并获取选定的文件夹
        File selectedDirectory = directoryChooser.showDialog(null);
        if (selectedDirectory != null) {
            // 用户选择了文件夹，处理文件夹
            File directory = new File(selectedDirectory.toString());
            if (directory.exists() && directory.isDirectory()) {
                // 获取目录下所有文件和目录
                File[] files = directory.listFiles();
                if (files != null) { // 确保文件数组不为空
                    for (File file : files) {
                        if (file.isFile()) { // 检查是否是文件
                            //System.out.println(file.getAbsolutePath()); // 输出文件名
                            if (file.getAbsolutePath().indexOf(".docx") > 0) {
                                continue;
                            }
                            if (file.getAbsolutePath().indexOf(".doc") > 0 || file.getAbsolutePath().indexOf(".xls") > 0 || file.getAbsolutePath().indexOf(".xlsx") > 0) {
                                String fileText = file.getAbsolutePath();
                                fileText = fileText + "——" + FileUtil.splitName(fileText);
                                // 处理选中的文件
                                if (state.equals("left")) {
                                    leftFlileDataList.add(fileText);
                                } else if (state.equals("right")) {
                                    rightFlileDataList.add(fileText);
                                }
                            }
                        }
                    }
                }
            } else {
                System.out.println("Directory does not exist or is not a directory.");
            }
        }
        notPresentFile();
    }

    @FXML
    protected void leftFileBtnClick() {
        xuanzeFile("left");
        addLeftClick();
    }

    @FXML
    protected void leftFilesBtnClick() {
        xuanzeFiles("left");
        addLeftClick();
    }

    @FXML
    protected void leftCleanBtnClick() {
        leftFlileDataList.clear();
    }

    public void addLeftClick() {
        if (addLeftClick == true) {
            return;
        }
        leftList.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                String selectedItem = (String) leftList.getSelectionModel().getSelectedItem();
                if (selectedItem != null) {
                    leftFlileDataList.remove(selectedItem); // 删除选中的条目
                }
            }
        });
        addLeftClick = true;
    }

    @FXML
    protected void rightFileBtnClick() {
        xuanzeFile("right");
        addRightClick();
    }

    @FXML
    protected void rightFilesBtnClick() {
        xuanzeFiles("right");
        addRightClick();
    }

    @FXML
    protected void rightCleanBtnClick() {
        rightFlileDataList.clear();
    }

    public void addRightClick() {
        if (addRightClick == true) {
            return;
        }
        rightList.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                String selectedItem = (String) rightList.getSelectionModel().getSelectedItem();
                if (selectedItem != null) {
                    rightFlileDataList.remove(selectedItem); // 删除选中的条目
                }
            }
        });
        addRightClick = true;
    }

//    @FXML
//    protected void bijiaoBtnClick() {
//        resultPeopleList.clear();
//        resultFlileDataList.clear();
//        resultList.setItems(resultFlileDataList);
//
//        List<People> leftPeopleList = new ArrayList();
//        List<People> rightPeopleList = new ArrayList();
//        List<String> returnList = new ArrayList();
//        String fileName = "";
//
//        if(leftFlileDataList.size()==0 || rightFlileDataList.size()==0){
//            System.out.println("返回");
//            return;
//        }
//
//        try {
//            for(String leftStr : leftFlileDataList){
//                String filePath = leftStr.split("——")[0];
//                String filePeopleName = leftStr.split("——")[1];
//                String[] strings = filePath.split("\\\\");
//                fileName = strings[strings.length-1]+"  ";
//                People people = null;
//                if(leftStr.indexOf(".doc") >= 0){
//                    people = FileUtil.toDoc(filePath);
//                }else if(leftStr.indexOf(".xlsx") >= 0){
//                    people = FileUtil.toXlsx(filePath);
//                }else if(leftStr.indexOf(".xls") >= 0){
//                    people = FileUtil.toXls(filePath);
//                }
//                if(people==null){
//                    continue;
//                }
//
//                people.setFileName(fileName+"  ");
//                people.setFilePeopleName(filePeopleName);
//                leftPeopleList.add(people);
//            }
//        }catch (Exception e){
//            returnList.add("A"+fileName+"   "+e.toString());
//        }
//
//        try {
//            for(String rightStr : rightFlileDataList){
//                String filePath = rightStr.split("——")[0];
//                String filePeopleName = rightStr.split("——")[1];
//                String[] strings = filePath.split("\\\\");
//                fileName = strings[strings.length-1]+"  ";
//                People people = null;
//                if(rightStr.indexOf(".doc") >= 0){
//                    people = FileUtil.toDoc(filePath);
//                }else if(rightStr.indexOf(".xlsx") >= 0){
//                    people = FileUtil.toXlsx(filePath);
//                }else if(rightStr.indexOf(".xls") >= 0){
//                    people = FileUtil.toXls(filePath);
//                }
//                if(people==null){
//                    continue;
//                }
//
//                people.setFileName(fileName+"  ");
//                people.setFilePeopleName(filePeopleName);
//                rightPeopleList.add(people);
//            }
//        }catch (Exception e){
//            returnList.add("B"+fileName+"   "+e.toString());
//        }
//
//        for(People leftPeople : leftPeopleList){
//            for(People rightPeople : rightPeopleList){
//                if(leftPeople.getFilePeopleName().equals(rightPeople.getFilePeopleName())){
//                    People bijiaoPeople = FileUtil.bijiaoPeople(leftPeople, rightPeople);
//                    List<String> bijiaoList = bijiaoPeople.getRemarkList();
//                    if(bijiaoList.size() > 0){
//                        bijiaoPeople.setFileName(leftPeople.getFileName());
//                        resultPeopleList.add(bijiaoPeople);
//                        String bijiaoStr = "";
//                        for(String bijiao : bijiaoList){
//                            bijiaoStr = bijiaoStr+" "+bijiao;
//                        }
//                        bijiaoStr = leftPeople.getFileName()+" "+bijiaoStr;
//                        returnList.add(bijiaoStr);
//                    }
//                }
//            }
//        }
//
//        for(String str : returnList){
//            resultFlileDataList.add(str);
//        }
//
//        Alert alert = new Alert(Alert.AlertType.INFORMATION);
////        alert.setTitle("Information Dialog");
//        alert.setHeaderText(null);
//        alert.setContentText("比对完成");
//
//        alert.showAndWait();
//    }

    @FXML
    private void initialize() {
        leftList.setItems(leftFlileDataList);
        leftList.setItems(leftFlileDataList);
        rightList.setItems(rightFlileDataList);
        rightList.setItems(rightFlileDataList);

        errorFileName.setSortable(false); // 禁用排序
        errorNumber.setSortable(false);
        errorDescribe.setSortable(false);
        errorDescribe.prefWidthProperty().bind(resultTableView.widthProperty().divide(1.2));

        errorFileName.setCellValueFactory(new PropertyValueFactory<>("fileName"));
        errorNumber.setCellValueFactory(new PropertyValueFactory<>("errorNumber"));
        errorDescribe.setCellValueFactory(new PropertyValueFactory<>("errorDescribe"));
        resultTableView.setItems(bijiaoResultList);
    }

    @FXML
    protected void bijiaoBtnClick() {
        resultPeopleList.clear();
//        bijiaoResultList.clear();
        resultRightPeopleList.clear();
        resultLeftPeopleList.clear();

        List<People> leftPeopleList = new ArrayList();
        List<People> rightPeopleList = new ArrayList();
        String fileName = "";

        if (leftFlileDataList.size() == 0 || rightFlileDataList.size() == 0) {
            System.out.println("返回");
            return;
        }

        try {
            for (String leftStr : leftFlileDataList) {
                String filePath = leftStr.split("——")[0];
                String filePeopleName = leftStr.split("——")[1];
                String[] strings = filePath.split("\\\\");
                fileName = strings[strings.length - 1] + "  ";
                People people = null;
                if (leftStr.indexOf(".doc") >= 0) {
                    people = FileUtil.toDoc(filePath);
                } else if (leftStr.indexOf(".xlsx") >= 0) {
                    people = FileUtil.toXlsx(filePath);
                } else if (leftStr.indexOf(".xls") >= 0) {
                    people = FileUtil.toXls(filePath);
                }
                if (people == null) {
                    continue;
                }

                people.setFileName(fileName + "  ");
                people.setFilePeopleName(filePeopleName);
                leftPeopleList.add(people);
            }
        } catch (Exception e) {
            bijiaoResultList.add(new BijiaoResult("A" + fileName, "", e.toString()));
        }

        try {
            for (String rightStr : rightFlileDataList) {
                String filePath = rightStr.split("——")[0];
                String filePeopleName = rightStr.split("——")[1];
                String[] strings = filePath.split("\\\\");
                fileName = strings[strings.length - 1] + "  ";
                People people = null;
                if (rightStr.indexOf(".doc") >= 0) {
                    people = FileUtil.toDoc(filePath);
                } else if (rightStr.indexOf(".xlsx") >= 0) {
                    people = FileUtil.toXlsx(filePath);
                } else if (rightStr.indexOf(".xls") >= 0) {
                    people = FileUtil.toXls(filePath);
                }
                if (people == null) {
                    continue;
                }

                people.setFileName(fileName + "  ");
                people.setFilePeopleName(filePeopleName);
                rightPeopleList.add(people);
            }
        } catch (Exception e) {
            bijiaoResultList.add(new BijiaoResult("B" + fileName, "", e.toString()));
        }

        for (People leftPeople : leftPeopleList) {
            for (People rightPeople : rightPeopleList) {
                if (leftPeople.getFilePeopleName().equals(rightPeople.getFilePeopleName())) {
                    People bijiaoPeople = FileUtil.bijiaoPeople(leftPeople, rightPeople);
                    List<String> bijiaoList = bijiaoPeople.getRemarkList();
                    if (bijiaoList.size() > 0) {
                        bijiaoPeople.setFileName(leftPeople.getFilePeopleName());
                        resultPeopleList.add(bijiaoPeople);
                        resultRightPeopleList.add(rightPeople);
                        resultLeftPeopleList.add(leftPeople);
                        String bijiaoStr = "";
                        for (String bijiao : bijiaoList) {
                            if(bijiaoStr.equals("")){
                                bijiaoStr = " " + bijiao;
                            }else{
                                bijiaoStr = bijiaoStr + " | " + bijiao;
                            }
                        }
                        bijiaoResultList.add(new BijiaoResult(leftPeople.getFilePeopleName(), bijiaoList.size() + "", bijiaoStr));
                    }
                    continue;
                }
            }
        }

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
//        alert.setTitle("Information Dialog");
        alert.setHeaderText(null);
        alert.setContentText("比对完成");

        alert.showAndWait();
    }

    @FXML
    protected void daochuBtnClick() {
        if (resultPeopleList.size()==0 || bijiaoResultList.size() == 0) {
            return;
        }
        for(int i=0;i<resultPeopleList.size();i++){
            FileUtil.createExcel(resultLeftPeopleList.get(i),resultRightPeopleList.get(i),resultPeopleList.get(i));
        }


        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText(null);
        alert.setContentText("导出完成");

        alert.showAndWait();
    }

    @FXML
    protected void bijiaoCleanBtnClick() {
        bijiaoResultList.clear();
    }


    public void notPresentFile(){
        bijiaoResultList.clear();
        if(leftFlileDataList.size()==0 || rightFlileDataList.size()==0){
            return;
        }
        List<String> b_indx_list = new ArrayList<>();
        for(int i=0;i<rightFlileDataList.size();i++){
            b_indx_list.add("false");
        }
        for (String leftStr : leftFlileDataList) {
            String leftFilePeopleName = leftStr.split("——")[1];
            boolean isCunzai = false;
            for(int j=0;j<rightFlileDataList.size();j++){
                String rightFilePeopleName = rightFlileDataList.get(j).split("——")[1];
                if(leftFilePeopleName.equals(rightFilePeopleName)){
                    isCunzai = true;
                    b_indx_list.set(j,"true");
                    break;
                }
            }
            if(isCunzai == false){
                bijiaoResultList.add(new BijiaoResult("A未找到匹配文件",  "", leftStr));
            }
        }

        for(int i=0;i<b_indx_list.size();i++){
            if(b_indx_list.get(i).equals("false")){
                bijiaoResultList.add(new BijiaoResult("B未找到匹配文件",  "", rightFlileDataList.get(i)));
            }
        }
    }

    @FXML
    protected void banquan() {
        System.out.println("点击我了");
        try {
            // 加载新窗口的FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("banquan.fxml"));
            Stage newWindow = new Stage();
            Scene scene = new Scene(loader.load(),500,500);
            newWindow.setScene(scene);
            newWindow.initStyle(StageStyle.UNDECORATED);
            newWindow.show();
        }catch (Exception e){

        }
    }



}